<?php
namespace app\api\controller;
use think\Controller;
use app\api\controller\Common;
use think\Db;
use think\Request;
use think\db\Where;
use think\input;
class Index extends Controller
{
// 用户登录获取用户登录openID
    public function getlogin(){
        $request=new Request();
        $code=$request->param("code");
        $appid="wx7cff958a038c1630";
        $secret="b54a30a68d3d3173743a24bd9f853901";
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        //获取GET请求
        function httpGet($url){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
            curl_setopt($curl, CURLOPT_URL, $url);
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
        }
        //发送
        $str = httpGet($api);
        exit($str);

    }
    
    // 首次进来获取用户信息
    public function firstgetuser(){
        $request=new Request();
        $openid=$request->param('openid');
        // 判断用户是否已经注册过
        $data=Db::name('userinfo')->where("openid",$openid)->find();
        // if(empty($data)){
        // }else{
            exit(json_encode($data,JSON_UNESCAPED_UNICODE));
        // }
    }
    // 首次登录进行注册    
    // 添加微信名称头像等信息
    public function adduserinfo(){
        $request=new Request();
        $openid=$request->param('openid');
        $nickName=$request->param('nickName');
        $avatarUrl=$request->param('avatarUrl');
        $data1=Db::name('userinfo')->where("openid",$openid)->find();
        if(empty($data1)){
            $data=[];
            $data["openid"]=$openid;
            $data["nickName"]=$nickName;
            $data["avatarUrl"]=$avatarUrl;
            $re=Db::name('userinfo')->insert($data);
            if($re){
                exit(json_encode($re,JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode($re,JSON_UNESCAPED_UNICODE));
            }
        }
    }
    // 团长端判断是否已经存在该团长
    public function havetuan(){
        $request=new Request();
        $openid=$request->get('openid');
        $data=Db::name('md')->where("openid",$openid)->find();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 上传图片
    public function upimg(){
        $request=new Request();
        $upimgobj=controller('Common');
        $image_error = $_FILES['file']['error'];
        if ($image_error == 4) {
            $img='';
        }else{
            $file=$request->file('file');
            if(!empty($file)){           
                 $img=$upimgobj->upaction1($file);
            }
        }
        exit($img);
    }
    // 申请开店
    public function apply()
    {
        $request=new Request();
        // $data1=$_POST;
        $openid=$request->post('openid');
        $mdname=$request->post('mdname');
        $nickName=$request->post('nickName');
        $avatarUrl=$request->post('avatarUrl');
        $md=$request->post('md');
        $adr=$request->post('adr');
        $num=$request->post('num');
        $phone=$request->post('phone');
        $xmname=$request->post('xmname');
        $mdimg=$request->post('mdimg');
        $mdtype=$request->post('mdtype');
        $yyzzimg=$request->post('yyzzimg');
        $startime=$request->post('starttime');
        $endtime=$request->post('endtime');
        $latitude=$request->post('latitude');
        $longitude=$request->post('longitude');
        $idimg1=$request->post('idimg1');
        $idimg2=$request->post('idimg2');
        $phone2=$request->post('phone2');
        $code=$request->post('yqcode');
        $data=[
            "openid"=>$openid,
            "mdname"=>$mdname,
            "nickName"=>$nickName,
            "avatarUrl"=>$avatarUrl,
            "md"=>$md,
            "mdnum"=>$num,
            "mdadr"=>$adr,
            "mdtype"=>$mdtype,
            "xmname"=>$xmname,
            "startime"=>$startime,
            "endtime"=>$endtime,
            "zzimg"=>$yyzzimg,
            "mdimg"=>$mdimg,
            "latitude"=>$latitude,
            "longitude"=>$longitude,
            "idimg1"=>$idimg1,
            "idimg2"=>$idimg2,
            "phone1"=>$phone,
            "phone2"=>$phone2,
            "code"=>$code
        ];
        $re=Db::name('md')->insert($data);
        exit($re);
    }
    // 获取所有店铺位置信息
    public function getthadr(){
        $where=['status'=>1,'mdstatus'=>1];
        $data=Db::name('md')->where($where)->select();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 上传图片
    // public function upload()
    // {
    //     $request=new Request();
    //     $file=$request->param('file');
    //     var_dump($request);
    //     // $res=$this->upaction($file);
        
    //     // exit($res);
    // }
    // 用户端首页拼团专区
    public function ptzq(){
        $where['pt']=array('eq',1);
        $where['status']=array('eq',1);
        $where['ptid']=array('neq',0);
        $data=Db::name('product')->field(['pid','tid','yid','pname','poldprice','pnewprice','pthumb','pnum'])->where(new where($where))->select();
        // var_dump($data);
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 用户端首页分类
    public function type(){
        $data=Db::name('type')->where('topid',0)->select();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 用户端首页分类产品
    // public function typep(){
    //     $data=Db::name('type')->where('topid',0)->select();
    //     exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    // }
    // 产品分类列表
    public function categories()
    {
        $topdata=Db::name('type')->where('topid',0)->select();
        $zidata=[];
        for($i=0;$i<count($topdata);$i++){
            // $where['pt']=array('eq',1);
            $where['status']=array('eq',1);
            // $where['ptid']=array('neq',0);
            $where['tid']=array('eq',$topdata[$i]['tid']);
            $da=Db::name('product')->field(['pid','tid','yid','pname','poldprice','pnewprice','pthumb','pnum'])->where(new where($where))->select();
            $zidata[$i]=$da;
        }
        $data=["topdata"=>$topdata,"zidata"=>$zidata];   
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 首页获取每日上新产品
    public function getnewp(){
        // 24小时86400，48小时前172800,72小时259200，10t
        $now=time()-864000;
        $time=time();
        $where['pt']=array('eq',1);
        $where['status']=array('eq',1);
        $where['ptid']=array('neq',0);
        $where['time']=array('between',"$now,$time");
        // ->where('time',"egt",$now)
        $data=Db::name('product')->field(['pid','tid','yid','pname','poldprice','pnewprice','pthumb','pnum'])->where(new where($where))->order("pid","DESC")->select();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 搜索商品
    public function search(){
        $request=new Request();
        $search=$request->param('query');
        // var_dump($name);exit;
        $where['pt']=array('eq',1);
        $where['status']=array('eq',1);
        $where['ptid']=array('neq',0);
        $where['pname']=array("like","%$search%");
        // ->where('time',"egt",$now)
        $data=Db::name('product')->field(['pid','tid','yid','pname','poldprice','pnewprice','pthumb','pnum'])->where(new where($where))->order("pid","DESC")->select();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 产品详细
    public function pdetail()
    {
        $request=new Request();
        $pid=$request->param('pid');
        $pro=Db::name('product')->where('pid',$pid)->find();
        // 添加拼团信息
        $ptdata=[];
        if($pro['pt']==1&&$pro['ptid']>0){
            $ptdata=Db::name('ptzq')->where('ptid',$pro['ptid'])->find();
            $ptsimg=$ptdata['ptstartime'];
            $pteimg=$ptdata['ptendtime'];
            $ptdata['ptstartime']=date('Y/m/d H:i:s',$ptsimg);
            $ptdata['ptendtime']=date('Y/m/d H:i:s',$pteimg);
            $ptdata['ptstartime1']=date('Y/m/d',$ptsimg);
            $ptdata['ptendtime1']=date('Y/m/d',$pteimg);
            // 添加拼团优惠信息
            $ptdata['ptyh']=[];
            if(!empty($ptdata)){
                $ptyh=Db::name('yhtype1')->where('yid',$ptdata['yid'])->find();
                $ptdata['ptyh']=$ptyh;
            }
        }
        // 添加产品优惠信息
        $yhdata=[];
        if($pro['yid']>0){
            $yhdata=Db::name('yhtype')->where('yid',$pro['yid'])->find();
        }
        $psx=Db::name('psx')->where('pid',$pid)->select();
        $data=["pro"=>$pro,"psx"=>$psx,"ptdata"=>$ptdata,"yhdata"=>$yhdata];
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    
    // 查找单个商品购物车
    public function findcart(){
        $request=new Request();
        $pid=$request->param('pid');
        $uid=$request->param('uid');
        $psid=$request->param('psid');
        $where=[
            'uid'=>$uid,
            'pid'=>$pid,
            'psid'=>$psid,
            ];
        $data=Db::name('cart')->where($where)->find();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 查找所有购物车
    public function findallcart(){
        $request=new Request();
        $uid=$request->param('uid');
        $data=Db::name('cart')->where('uid',$uid)->select();
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    // 添加购物车
    public function addcart(){
        $request=new Request();
        $pid=$request->param('pid');
        $uid=$request->param('uid');
        $num=$request->param('num');
        $pname=$request->param('pname');
        $psid=$request->param('psid');
        $psname=$request->param('psname');
        $price=$request->param('price');
        $pthumb=$request->param('pthumb');
        $data=[
            'uid'=>$uid,
            'pid'=>$pid,
            'num'=>$num,
            'pname'=>$pname,
            'psname'=>$psname,
            'psid'=>$psid,
            'price'=>$price,
            'pthumb'=>$pthumb
            ];
        $res=Db::name('cart')->insert($data);
        exit(json_encode($res,JSON_UNESCAPED_UNICODE));
    }
    // 修改购物车
    public function upcart(){
        $request=new Request();
        $cid=$request->param('cid');
        $num=$request->param('num');
        
        $price=$request->param('price');
        $data=[
            'cid'=>$cid,
            'num'=>$num,
            
            'price'=>$price
            ];
        $res=Db::name('cart')->update($data);
        exit(json_encode($res,JSON_UNESCAPED_UNICODE));
    }
    // 删除购物车
    public function delcart(){
        $request=new Request();
        $cart=$request->param('cart');
        $cart=json_decode($cart);
        // var_dump($cart);
        for($i=0;$i<count($cart);$i++){
            $res=Db::name('cart')->delete($cart['cid']);
        }
        
        // exit(json_encode($res,JSON_UNESCAPED_UNICODE));
    }
    // 商品详情页获取相关12条商品推荐
    public function gettj(){
        $request=new Request();
        $tid=$request->param('tid');
        $whe=["tid"=>$tid,"status"=>1];
        $res=Db::name('product')->field(['pid','tid','yid','pname','poldprice','pnewprice','pthumb','pnum'])->where($whe)->limit(12)->select();
        exit(json_encode($res,JSON_UNESCAPED_UNICODE));
    }
    // 支付获取token
    public function gettoken(){
        $appid="wx7cff958a038c1630";
        $secret="b54a30a68d3d3173743a24bd9f853901";
        
        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        
        //获取GET请求
        function httpGet($url){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
            curl_setopt($curl, CURLOPT_URL, $url);
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
        }
        //发送
        $str = httpGet($api);
        exit($str);
    }
    public function addorder(){
            $uid=input("post.uid");
            $mdid=input("post.mdid");
            $num=input("post.totalNum");
            $orderpice=input("post.order_price");
            $goods=input("post.goods");
            // $goods=json_decode($goods);
            $dbp=Db::name('product');
            $dbps=Db::name('psx');
            // 判断商品是否已经卖完了
            foreach ($goods as $key=>$val){
                // 没有属性的商品
                if($val['psid']==0){
                    $da=$dbp->removeOption('where')->removeOption('field')->field(['pnum','salenum'])->where('pid',$val['pid'])->find();
                    if($da['pnum']<=$da['salenum']){
                        $error="商品“".$val['pname']."”已售罄请另选商品";
                        $resdata=["da"=>'',"msg"=>$error];
                        exit(json_encode($resdata,JSON_UNESCAPED_UNICODE));
                    }
                // 有属性的商品
                }else{
                    $da=$dbps->removeOption('where')->removeOption('field')->field(['allnum','salenum'])->where('psid',$val['psid'])->find();
                    if($da['allnum']<=$da['salenum']){
                        $error="商品“".$val['pname']."”的“".$val['psname']."”系列已售罄请另选属性或商品";
                        $resdata=["da"=>'',"msg"=>$error];
                        exit(json_encode($resdata,JSON_UNESCAPED_UNICODE));
                    }
                }
    
            }
            // 没卖完继续执行
            $data=[
                "code"=>time().$uid,
                "uid"=>$uid,
                "time"=>time(),
                "money"=>$orderpice,
                "uptime"=>time(),
                "mdid"=>$mdid,
                "num"=>$num
                ];
            $rest=Db::name('orders')->insertGetId($data);
            if($rest>0){
                // $dbo=Db::name('orderone');
                foreach($goods as $key=>$v){
                    $oda=[
                        "oid"=>$rest,
                        "uid"=>$uid,
                        "oocode"=>time().$uid.$rest.$v['psid'],
                        "pid"=>$v['pid'],
                        "psid"=>$v['psid'],
                        "pname"=>$v['pname'],
                        "psname"=>$v['psname'],
                        "num"=>$v['num'],
                        "price"=>$v['price'],
                        "thumb"=>$v['thumb'],
                        "time"=>time()
                        ];
                    Db::name('orderone')->insert($oda);
                }
            }
            $result=Db::name('orders')->field(['code'])->where('oid',$rest)->find();
            $resdata=["da"=>$result['code'],"msg"=>"系统繁忙请稍后在试"];
            exit(json_encode($resdata,JSON_UNESCAPED_UNICODE));
        }
    public function getorder(){
        $request=new Request();
        $status=$request->param('status');
        $uid=$request->param('uid');
        $dd=[];
        if($status==-1){
             $data=Db::name('orderone')->where('uid',$uid)->order("time","DESC")->select();
             foreach ($data as $key=>$value){
		        $data[$key]['time']=date("Y-m-d H:i:s",$value['time']);
		        }
        }else if($status==0){
            $where=[
                "uid"=>$uid,
                "zfstatus"=>$status
                ];
            $dat=Db::name('orders')->field(['oid'])->where($where)->order("time","DESC")->select();
            if(count($dat)>0){
                $data=[];
                for($i=0;$i<count($dat);$i++){
                    $da1=Db::name('orderone')->where('oid',$dat[$i]['oid'])->order("time","DESC")->select();
                    foreach ($da1 as $key=>$val){
		                $da1[$key]['time']=date("Y-m-d H:i:s",$val['time']);
		                array_push($data,$da1[$key]);
		            }
                }
            }else{
                $data=[];
            }
        }else{
            $where=[
                "uid"=>$uid,
                "ddstatus"=>$status
                ];
            $data=Db::name('orderone')->where($where)->order("time","DESC")->select();
            foreach ($data as $key=>$v){
		        $data[$key]['time']=date("Y-m-d H:i:s",$v['time']);
		        }
        }
        count($data)>0?$dd=$data:$dd=[];
        exit(json_encode($dd,JSON_UNESCAPED_UNICODE));
    }
    // 获取各种订单的数量
    public function getordernum(){
        $request=new Request();
        $uid=$request->param('uid');
        $one=0;
        $two=0;
        $three=0;
        $four=0;
        $five=0;
        $where1=[
            "uid"=>$uid,
            "zfstatus"=>0
            ];
        $dat=Db::name('orders')->field(['oid'])->where($where1)->order("time","DESC")->select();
        if(count($dat)>0){
            for($i=0;$i<count($dat);$i++){
                $num=Db::name('orderone')->where('oid',$dat[$i]['oid'])->count();
                $one+=$num;
            }
        }
        $where2=[
            "uid"=>$uid,
            "ddstatus"=>2
            ];
            $two=Db::name('orderone')->where($where2)->count();
        $where3=[
            "uid"=>$uid,
            "ddstatus"=>3
            ];
        $three=Db::name('orderone')->where($where3)->count();
        $where4=[
            "uid"=>$uid,
            "ddstatus"=>4
            ];
        $four=Db::name('orderone')->where($where4)->count();
        $where5=[
            "uid"=>$uid,
            "ddstatus"=>5
            ];
        $five=Db::name('orderone')->where($where5)->count();
        
        $data=["one"=>$one,"two"=>$two,"three"=>$three,"four"=>$four,"five"=>$five];
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));    
    }
}
